<template>
  <div class="company-archive-container">
    <el-form :inline="true" :model="filterForm" class="filter-form">
      <div class="page-title">
        <h1>企业档案管理</h1>
      </div>
      
      <el-form-item label="公司名称">
        <el-input v-model="filterForm.name" placeholder="公司全称"></el-input>
      </el-form-item>
      
      <el-form-item label="公司类型">
        <el-select v-model="filterForm.type" placeholder="公司类型">
          <el-option 
            v-for="item in companyTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
      </el-form-item>
      
      <el-form-item>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" round @click="showAddDialog">新增公司</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增公司对话框 -->
    <el-dialog title="新增公司信息" v-model="addDialogVisible" width="800px">
      <el-form :label-position="labelPosition" label-width="120px" :model="newCompany" ref="addFormRef">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司ID" required>
              <el-input v-model="newCompany.id"></el-input>
            </el-form-item>
            <el-form-item label="社会信用代码" required>
              <el-input v-model="newCompany.creditCode" placeholder="统一社会信用代码（18位）"></el-input>
            </el-form-item>
            <el-form-item label="公司名称" required>
              <el-input v-model="newCompany.name"></el-input>
            </el-form-item>
            <el-form-item label="公司地址" required>
              <el-input v-model="newCompany.address"></el-input>
            </el-form-item>
            <el-form-item label="公司类型" required>
              <el-select v-model="newCompany.type" placeholder="请选择公司类型" style="width:100%">
                <el-option 
                  v-for="item in companyTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="公司法人" required>
              <el-input v-model="newCompany.legalPersonName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="企业人数" required>
              <el-input v-model="newCompany.personNumber" type="number" placeholder="员工总人数"></el-input>
            </el-form-item>
            <el-form-item label="注册资本" required>
              <el-input v-model="newCompany.registerCapital">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="成立时间" required>
              <el-date-picker 
                v-model="newCompany.establishDate" 
                type="date" 
                placeholder="选择日期"
                style="width:100%">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="年度营收">
              <el-input v-model="newCompany.annualRevenue">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="年度税收">
              <el-input v-model="newCompany.annualTax">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="年度利润">
              <el-input v-model="newCompany.annualProfit">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="租赁面积">
              <el-input v-model="newCompany.rentArea">
                <template #append>平方米</template>
              </el-input>
            </el-form-item>
            <el-form-item label="租期">
              <el-input v-model="newCompany.rentTime" placeholder="例如：3年">
              </el-input>
            </el-form-item>
            <el-form-item label="租金">
              <el-input v-model="newCompany.rentMoney">
                <template #append>元/平方米/月</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAddCompany">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="合同状态" v-model="contractDialogVisible" width="50%">
      <el-input
        type="textarea"
        :autosize="{ minRows: 10, maxRows: 20}"
        placeholder="合同内容"
        v-model="currentCompany.contractContent"
        readonly>
      </el-input>

     <div style="margin-top: 20px; text-align: right;">
        <el-tag v-if="currentCompany.contractPass === 1" type="success" effect="dark">
          合同已审批
        </el-tag>
        <el-tag v-else type="danger" effect="dark">
          合同未审批
        </el-tag>
     </div>


      <template #footer>
        <el-button @click="contractDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 租赁空间对话框 -->
    <el-dialog title="租赁空间信息" v-model="rentDialogVisible" width="30%">
      <el-form :label-position="labelPosition" label-width="100px" :model="currentCompany">
        <el-form-item label="租赁面积">
          <el-link type="info">{{ currentCompany.rentArea }} 平方米</el-link>
        </el-form-item>
        <el-form-item label="租期">
          <el-link type="info">{{ currentCompany.rentTime }}</el-link>
        </el-form-item>
        <el-form-item label="租金">
          <el-link type="info">{{ currentCompany.rentMoney }} 元/平方米/月</el-link>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="rentDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 公司列表表格 -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="公司ID" width="100" fixed />
      <el-table-column prop="name" label="公司名称" width="120" fixed />
      <el-table-column prop="creditCode" label="社会信用代码" width="180" />
      <el-table-column prop="personNumber" label="企业人数" width="100" />
      <el-table-column prop="type" label="公司类型" width="120">
        <template #default="scope">
          {{ getCompanyTypeLabel(scope.row.type) }}
        </template>
      </el-table-column>
      <el-table-column prop="legalPersonName" label="法定代表人" width="120" />
      <el-table-column prop="registerCapital" label="注册资本" width="120">
        <template #default="scope">
          {{ scope.row.registerCapital }} 万元
        </template>
      </el-table-column>
      <el-table-column prop="annualRevenue" label="年度营收" width="120">
        <template #default="scope">
          {{ scope.row.annualRevenue }} 万元
        </template>
      </el-table-column>
      <el-table-column prop="annualTax" label="年度税收" width="120">
        <template #default="scope">
          {{ scope.row.annualTax }} 万元
        </template>
      </el-table-column>
      <el-table-column prop="annualProfit" label="年度利润" width="120">
        <template #default="scope">
          {{ scope.row.annualProfit }} 万元
        </template>
      </el-table-column>
      <el-table-column prop="address" label="公司地址" width="140" />
      <el-table-column prop="establishDate" label="成立时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.establishDate) }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="scope">
          <el-button @click="showContractDialog(scope.row)" type="text" size="mini">合同状态</el-button>
          <el-button @click="showRentDialog(scope.row)" type="text" size="mini">租赁空间</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 记录总数和分页 -->
    <div class="pagination-info">
      <div class="total-count">共 {{ total }} 条记录</div>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
        class="pagination-container">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  // 从环境变量中获取基础地址（自动适配开发/生产环境）
  baseURL: import.meta.env.VITE_API_BASE_URL,
  // 可选：添加超时时间等其他配置
  timeout: 10000
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const pageSize = ref(10)
const currentPage = ref(1)

// 在组件挂载时获取数据
onMounted(() => {
  fetchCompanies()
})


// 获取公司列表（适配后端PageBean结构）
const fetchCompanies = async (params = {}) => {
  try {
    // 合并分页参数和查询参数
    const queryParams = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...params
    }
    
    const response = await api.get('/api/companypage', { params: queryParams })
    
    // 后端返回格式为：Result{data: PageBean{total: Long, companies: List<Company>}}
    // 解析分页数据
    const pageBean = response.data.data || {}
    tableData.value = pageBean.companies || []  // 从PageBean中获取公司列表
    total.value = pageBean.total || 0           // 从PageBean中获取总条数
  } catch (error) {
    ElMessage.error('获取公司列表失败: ' + (error.response?.data?.message || error.message))
  }
}

// 查询
const handleQuery = async () => {
  // 重置到第一页
  currentPage.value = 1
  // 传递查询参数
  await fetchCompanies({
    name: filterForm.name,
    type: filterForm.type
  })
}

// 确认新增公司
const confirmAddCompany = async () => {
  try {
    // 表单验证
    if (!validateForm(newCompany)) {
      return
    }
    
    const response = await api.post('/api/companyrentinsert', newCompany)
    
    // 新增成功后刷新列表
    ElMessage.success("新增公司成功")
    addDialogVisible.value = false
    fetchCompanies()
    
    // 重置表单
    resetAddForm()
  } catch (error) {
    ElMessage.error('新增公司失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除公司
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该公司信息, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await api.delete(`/api/companydelete/${row.id}`)
    ElMessage.success('删除成功!')
    // 重新获取列表
    fetchCompanies()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message))
    }
  }
}

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page
  fetchCompanies({
    name: filterForm.name,
    type: filterForm.type
  })
}

// 公司类型选项
const companyTypeOptions = [
  { value: 1, label: '制造业' },
  { value: 2, label: '信息技术' },
  { value: 3, label: '金融业' },
  { value: 4, label: '教育培训' },
  { value: 5, label: '医疗健康' },
  { value: 6, label: '零售业' },
  { value: 7, label: '物流运输' },
  { value: 8, label: '建筑工程' },
  { value: 9, label: '餐饮服务' },
  { value: 10, label: '文化娱乐' },
  { value: 11, label: '房地产' },
  { value: 12, label: '能源环保' },
  { value: 13, label: '农业' },
  { value: 14, label: '旅游酒店' },
  { value: 15, label: '媒体广告' },
  { value: 16, label: '咨询服务' },
  { value: 17, label: '其他行业' }
]

// 根据value获取公司类型标签
const getCompanyTypeLabel = (value) => {
  const type = companyTypeOptions.find(item => item.value === value)
  return type ? type.label : value
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  // 如果是字符串类型的日期，尝试转换
  if (typeof date === 'string') {
    // 处理不同格式的日期字符串
    if (date.includes('T')) {
      return date.split('T')[0]
    }
    return date
  }
  // 如果是Date对象
  if (date instanceof Date) {
    return date.toISOString().split('T')[0]
  }
  // 尝试将时间戳转换为日期
  if (typeof date === 'number') {
    return new Date(date).toISOString().split('T')[0]
  }
  return ''
}

// 对话框状态
const addDialogVisible = ref(false)
const contractDialogVisible = ref(false)
const rentDialogVisible = ref(false)
const labelPosition = ref('left')

// 当前操作的公司
const currentCompany = reactive({
  id: "",
  name: "",
  type: "",
  legalPersonName: "",
  registerCapital: "",
  annualRevenue: "",
  annualTax: "",
  annualProfit: "",
  address: "",
  establishDate: "",
  contractContent: "",
  contractPass: 0,// 后端用Integer：0=未审批，1=已审批
  rentArea: "",
  rentTime: "",
  rentMoney: 1,
  creditCode: "",
  personNumber: 0
})

// 生成默认合同内容
const generateDefaultContract = (company) => {
  const startDate = new Date(company.establishDate)
  const endDate = new Date(startDate)
  endDate.setFullYear(endDate.getFullYear() + 3)
  
  return `智慧园区企业入驻合同

合同编号：${new Date().getFullYear()}-${Math.floor(Math.random() * 10000).toString().padStart(4, '0')}

甲方（出租方）：XX智慧园区管理有限公司
地址：XX市XX区XX科技园1号楼
法定代表人：李园区
联系电话：400-888-XXXX

乙方（承租方）：${company.name}
社会信用代码：${company.creditCode || '未提供'}
企业人数：${company.personNumber || 0}人
公司类型：${getCompanyTypeLabel(company.type)}
法定代表人：${company.legalPersonName}
注册资本：${company.registerCapital}万元
注册地址：${company.address}

第一条 租赁标的：甲方将园区内${company.rentArea}平方米租赁给乙方使用。

第二条 合同期限：租赁期自${formatDate(company.establishDate)}起至${formatDate(endDate)}止。

第三条 租金及支付：租金标准：${company.rentMoney}元/平方米/月，合计年租金：${Math.round(company.rentMoney * parseInt(company.rentArea) * 12 / 10000)}万元。

第四条 权利义务：
1. 甲方提供基础设施及智慧园区服务；
2. 乙方按时缴纳费用并遵守园区规定；
3. 乙方不得擅自改变房屋用途。

第五条 违约责任：逾期支付租金需按日支付0.05%的滞纳金。

甲方（盖章）：___________________
乙方（盖章）：___________________
签订日期：_______________________`
}

// 筛选表单
const filterForm = reactive({
  name: "",
  type: ""
})

// 新增公司表单
const newCompany = reactive({
  id: "",
  name: "",
  type: "",
  legalPersonName: "",
  registerCapital: "",
  annualRevenue: "",
  annualTax: "",
  annualProfit: "",
  address: "",
  establishDate: "",
  contractContent: "",
  contractPass: 0,
  rentArea: "",
  rentTime: "",
  rentMoney: 1,
  creditCode: "",
  personNumber: 0
})

// 表单验证
const validateForm = (form) => {
  if (!form.id) {
    ElMessage.warning('请输入公司ID')
    return false
  }
  if (!form.creditCode) {
    ElMessage.warning('请输入社会信用代码')
    return false
  }
  if (form.creditCode.length !== 18) {
    ElMessage.warning('社会信用代码应为18位')
    return false
  }
  if (!form.personNumber || form.personNumber <= 0) {
    ElMessage.warning('请输入有效的企业人数（大于0）')
    return false
  }
  if (!form.name) {
    ElMessage.warning('请输入公司名称')
    return false
  }
  if (!form.type) {
    ElMessage.warning('请选择公司类型')
    return false
  }
  if (!form.legalPersonName) {
    ElMessage.warning('请输入法定代表人')
    return false
  }
  if (!form.registerCapital) {
    ElMessage.warning('请输入注册资本')
    return false
  }
  if (!form.establishDate) {
    ElMessage.warning('请选择成立时间')
    return false
  }
  if (!form.address) {
    ElMessage.warning('请输入公司地址')
    return false
  }
  return true
}

// 重置新增表单
const resetAddForm = () => {
  Object.assign(newCompany, {
    id: "",
    name: "",
    type: "",
    legalPersonName: "",
    registerCapital: "",
    annualRevenue: "",
    annualTax: "",
    annualProfit: "",
    address: "",
    establishDate: "",
    contractContent: "",
    contractPass: 0,
    rentArea: "",
    rentTime: "",
    rentMoney: 1,
    creditCode: "",
    personNumber: 0
  })
}

// 重置查询条件
const handleReset = () => {
  filterForm.name = ''
  filterForm.type = ''
  // 重置后重新查询
  currentPage.value = 1
  fetchCompanies()
}

// 显示新增对话框
const showAddDialog = () => {
  resetAddForm()
  addDialogVisible.value = true
}

// 显示合同对话框：处理后端返回的CompanyRentVO数据
const showContractDialog = async (row) => {
  try {
    // 调用后端接口获取CompanyRentVO数据
    const response = await api.get(`/api/companyrent/${row.id}`);
    const companyRentData = response.data.data; // 后端返回的CompanyRentVO对象
    
    // 合并基础公司信息（从表格行数据）和后端返回的合同租赁数据
    Object.assign(currentCompany, row, companyRentData);
    
    // 如果没有合同内容，生成默认合同
    if (!currentCompany.contractContent) {
      currentCompany.contractContent = generateDefaultContract(currentCompany);
    }
    
    contractDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取公司合同信息失败: ' + (error.response?.data?.message || error.message));
  }
};

// 显示租赁对话框：处理后端返回的CompanyRentVO数据
const showRentDialog = async (row) => {
  try {
    // 调用后端接口获取CompanyRentVO数据
    const response = await api.get(`/api/companyrent/${row.id}`);
    const companyRentData = response.data.data; // 后端返回的CompanyRentVO对象
    
    // 合并基础公司信息和后端返回的租赁数据
    Object.assign(currentCompany, row, companyRentData);
    
    rentDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取公司租赁信息失败: ' + (error.response?.data?.message || error.message));
  }
};
</script>

<style scoped>
.company-archive-container {
  background-color: white;
  width: auto;
  padding: 30px;
}

.page-title {
  text-align: center;
  margin: 20px 0;
}

.filter-form {
  margin-bottom: 20px;
}

/* 统一控制输入元素宽度 */
:deep(.el-input),
:deep(.el-select) {
  width: 220px;
}

/* 对话框表单项目间距 */
.el-dialog .el-form-item {
  margin-bottom: 18px;
}

/* 按钮间距 */
.el-form-item:last-child {
  margin-right: 0;
}

/* 分页和记录总数样式 */
.pagination-info {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

.pagination-container {
  margin: 0;
}

/* 表格单元格内容居中 */
.el-table :deep(.cell) {
  text-align: center;
}
</style>
